/**
 * 通告指定商户范围
 */
angular.module('inspinia',['angularFileUpload']).controller("noticeMerchantSettings", function($scope, $http, $state, $stateParams,$filter,i18nService,SweetAlert,$document,FileUploader) {
	//涮新页面跳转最顶端
	window.scrollTo(0, 0);
	//数据源
	$scope.noticeId = $stateParams.noticeId;
	$scope.bool=[{text:"是",value:"1"},{text:"否",value:"0"}];
	$scope.noticeTypes=[{text:"全部",value:''},{text:"图文类",value:'0'},{text:"图片类",value:'1'}];
	$scope.noticeTypesStr = angular.toJson($scope.noticeTypes);
	$scope.paginationOptions=angular.copy($scope.paginationOptions);
	i18nService.setCurrentLang('zh-cn');  //设置语言为中文
	$scope.queryInfo = {merchantName: '', merchantNo: '', noticeId: $stateParams.noticeId, ntId: $stateParams.noticeId};
	$scope.queryFunc = function(){
		$scope.result=[];
		$http.post("notice/pageNoticeMerScope"
			, "queryInfo=" + angular.toJson($scope.queryInfo)
			+ "&pageNo=" + $scope.paginationOptions.pageNo
			+ "&pageSize=" + $scope.paginationOptions.pageSize
			, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
		)
			.success(function (data) {
				$scope.result = data.result;
				$scope.queryResultGrid.totalItems = data.totalCount;
			});
	}

    $scope.queryResultGrid = {
		data: 'result',
		paginationPageSize: 10,                  //分页数量
		paginationPageSizes: [10, 20, 50, 100],	  //切换每页记录数
		useExternalPagination: true,		  //开启拓展名
		enableHorizontalScrollbar: true,        //横向滚动条
		enableVerticalScrollbar: true,  		//纵向滚动条
		columnDefs: [
			{field: 'id',displayName: 'ID',width:90,pinnable: false,sortable: false},
			{field: '业务级',displayName: '业务组',width:180,visible:false},
			{field: 'merchantName',displayName: '商户名称',width:240,pinnable: false,sortable: false},
			{field: 'merchantNo',displayName: '商户编号',width:240,pinnable: false,sortable: false},
			{field: 'mobilephone',displayName: '用户手机号',width:240,pinnable: false,sortable: false},
			{field: 'createTime',displayName: '创建时间',width:180,pinnable: false,sortable: false,cellFilter:'date:"yyyy-MM-dd HH:mm:ss"'},
			{field: 'operator',displayName: '创建人',width:150,pinnable: false,sortable: false},
			{field: 'action',displayName: '操作',width: 200,pinnable: false,sortable: false,editable:true,cellTemplate:
				'<div class="lh30">' +
					'<a ng-click="grid.appScope.delNoticeMerScope(row.entity)">删除</a>' +
					'</div>'}
		],
		onRegisterApi: function(gridApi) {
			gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
				$scope.paginationOptions.pageNo = newPage;
				$scope.paginationOptions.pageSize = pageSize;
				$scope.queryFunc();
			});
		}
	 };

    $scope.queryFunc();
    $scope.delNoticeMerScope = function(entity){
    	SweetAlert.swal({
            title: "确认删除？",
//            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "提交",
            cancelButtonText: "取消",
            closeOnConfirm: true,
            closeOnCancel: true },
	        function (isConfirm) {
	            if (isConfirm) {
					$scope.delNoticeMerScopeRecord(entity);
	            }
        });
    }

    $scope.showAddNoticeMerScopeModal = function (){
		$scope.addInfo.queryKey = "";
		$scope.addInfo.merchantNo = "";
		$scope.addInfo.merchantName = "";
		$("#addNoticeMerScopeModal").modal("show");
	}

	$scope.addNoticeMerScope = function (){
    	if($scope.addInfo.merchantNo === ""){
			$scope.notice("商户不存在！");
    		return;
		}
    	const data = "teamId=" + $scope.addInfo.teamId
			+ "&merchantNo=" + $scope.addInfo.merchantNo
			+ "&noticeId=" + $scope.addInfo.noticeId
			+ "&merchantName=" + $scope.addInfo.merchantName;
		$http.post("notice/service/addNoticeMerScopeRecord", data
			, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
		)
			.success(function (data) {
				$scope.notice("添加成功！");
				if(data.status){
					$scope.queryFunc();
				}
			});
	}

	$scope.delNoticeMerScopeRecord = function (entity){
    	const data = "teamId=" + entity.teamId
			+ "&id=" + entity.id
			+ "&noticeId=" + entity.ntId
			+ "&merchantNo=" + entity.merchantNo
			+ "&merchantName=" + entity.merchantName;
		$http.post("notice/service/delNoticeMerScopeRecord", data
			, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
		)
			.success(function (data) {
				$scope.notice("删除成功！");
				if(data.status){
					$scope.queryFunc();
				}
			});
	}

	$scope.addInfo = {teamId: "", merchantName: "", merchantNo: "", queryKey: "", noticeId: $stateParams.noticeId};
	$scope.queryMerInfo = function () {
		if (this.addInfo.queryKey === "") {
			$scope.addInfo.merchantNo = "";
			$scope.addInfo.merchantName = "";
			return;
		}
		$http.post("notice/service/queryMerInfo", "queryKey=" + this.addInfo.queryKey
			, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
		)
			.success(function (data) {
				console.log(data);
				if (data.merInfo != undefined) {
					$scope.addInfo.teamId = data.merInfo.team_id;
					$scope.addInfo.merchantNo = data.merInfo.merchant_no;
					$scope.addInfo.merchantName = data.merInfo.merchant_name;
				} else {
					$scope.addInfo.merchantNo = "";
					$scope.addInfo.merchantName = "";
				}
			});
	}

	$scope.resetForm=function(){
		$scope.queryInfo.merchantName = "";
		$scope.queryInfo.merchantNo = "";
		$scope.queryInfo.mobilephone = "";
	}

	//页面绑定回车事件
	$document.bind("keypress", function(event) {
		$scope.$apply(function (){
			if(event.keyCode == 13){
				$scope.queryFunc();
			}
		})
	});

	$scope.showImportNoticeMerScopeModal = function (){
		$("#importNoticeMerScopeModal").modal("show");
	}

	//上传文件,定义控制器路径
	$scope.uploader = new FileUploader({
		url: 'notice/importData',
		queueLimit: 1,   //文件个数
		removeAfterUpload: true,  //上传后删除文件
		headers : {'X-CSRF-TOKEN' : $scope.csrfData},
		formData:[{channelCode:""}]
	});

	//过滤格式
	$scope.uploader.filters.push({
		name: 'fileFilter',
		fn: function(item /*{File|FileLikeObject}*/, options) {
			var type = '|' + item.name.slice(item.name.lastIndexOf('.') + 1) + '|';
			return '|xlsx|xls|'.indexOf(type) !== -1;
		}
	});

	//批量导入提交数据
	$scope.importInfo = {importType: "0", noticeId: $stateParams.noticeId};
	$scope.importStatus = false;
	$scope.importData = function(){
		$scope.importStatus = true;
		if($scope.uploader.queue.length===0){
			$scope.notice("请选择文件！");
			$scope.importStatus = false;
			return;
		}
		$scope.uploader.queue[0].formData[0].noticeId = $scope.importInfo.noticeId;
		$scope.uploader.queue[0].formData[0].importType = $scope.importInfo.importType;
		if($scope.uploader.queue.length > 0){
			$scope.uploader.uploadAll();
			$scope.uploader.onSuccessItem = function(fileItem, response, status, headers) {//上传成功后的回调函数，在里面执行提交
				$scope.importStatus = false;
				$scope.notice(response.msg);
				$scope.queryFunc();
			};
		}
	}
});
